require("../util.js");
require("../component/components.js");
require("../../jsMt/util.js");
var userInfo=JSON.parse(sessionStorage.getItem("userInfo"));
if(!userInfo){
    location.href="/loginIndex"
}
var vm = new Vue({
    el:"#shoppingCart",
    data:{
        uid:userInfo.id,
        cartList:{},
        integralList:[],
        totalMoney:"",
        type:""
    },
    mounted:function(){
        this.getCartList();
    },
    methods:{
        //后退
        getBack:function(){
            // history.go(-1);
            location.href="/purchase"
        },
        bgimg:function(url){
            url = url?url:"";
            return {
                "background-image":'url("'+url+'"),url("")'
            }
        },
        //购物车列表
        getCartList:function(){
            var that=this;
            this.ajax({url:"/purchase/cartList",data:{loginUid:that.uid},dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.cartList=b.json.data;
                }else{
                    vm.$refs.prompt.toast("获取列表失败！")
                }
            });
        },
        //修改购物车数量
        updateCart:function(type,item,index,index1){
            var that=this,number;
            console.log(that.integralList)
            console.log(index1)
            console.log(that.integralList[index1]);
            if(type==1){
                if(item.number==item.productNumber){
                    vm.$refs.prompt.toast("宝贝不能再增多了！");
                    return false;
                }else{
                    item.number+=1;
                }
            }else if(type==2){
                if(item.number==1){
                    vm.$refs.prompt.toast("宝贝不能再减少了！");
                    return false;
                }else{
                    item.number-=1;
                }
            }
            var data={
                loginUid:that.uid,
                number:item.number,
                cartId:item.cartId
            };
            console.log(data)
            this.ajax({url:"/purchase/updateCart",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    that.getCartList();
                    that.countMoney();
                    // that.cartList.forEach(function(val){
                    //     val.products.forEach(function(key){
                    //         if(item.cartId==key.cartId){
                    //             // if(type==1){
                    //             //     key.number+=1;
                    //             // }else if(type==2){
                    //             //     key.number-=1;
                    //             // }
                    //             // key.number=b.json.data;
                    //         }
                    //     });
                    // });
                }else{
                    vm.$refs.prompt.toast("修改数量失败！");
                }
            });
        },
        //删除购物车
        deleteCartByid:function(cartId){
            var that=this,data;
            data={
                loginUid:that.uid
            };
            if(cartId){
                data.cartId=cartId;
                $(".list-centLeft").removeClass("swipeleft");
            }else{
                data.cartId=that.integralList.join(",");

            }
            console.log(data)
            that.ajax({url:"/purchase/deleteCartByid",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    location.href="/purchase/shoppingCart";
                }else{
                    vm.$refs.prompt.toast(b.json.msg||"移除无效商品失败！");
                }
            });
        },
        compareDate:function(item){
            var that=this;
            var second=getCompareDate(item.currentTime,item.limitTime,"second");
            return second;
        },
        //时分秒倒计时
        leftTimer:function(item,index,ins){
            var that=this;
            that.$nextTick(function(){
                var second=getCompareDate(item.currentTime,item.limitTime,"second");
                addTimer("data"+index+ins,second);
            });
        },
        //全选（取消）
        getCheckedAll:function(){
            var that=this;
            var checkboxCart=$(".checkboxCart");
            var shoppingCart=$(".shoppingCart");
            var len=shoppingCart.find("input[type=checkbox]");
            if(checkboxCart.hasClass("shoppingCart-select")){
                checkboxCart.removeClass("shoppingCart-select");
                shoppingCart.find(".shoppingCart-listTitle").removeClass("shoppingCart-select");
                that.integralList=[];
                that.totalMoney="";
            }else{
                checkboxCart.addClass("shoppingCart-select");
                shoppingCart.find(".shoppingCart-listTitle").addClass("shoppingCart-select");
                for(var i=0;i<=len.length;i++){
                    if(len.eq(i).prop("disabled")==false){
                        console.log(len.eq(i).val())
                        that.integralList.push(len.eq(i).val());
                        that.totalMoney=Number(that.totalMoney)+Number(len.eq(i).val());
                    }
                }
            }
            console.log(that.totalMoney)
        },
        //总钱数
        countMoney:function(){
            var that=this;
            console.log("dddddddd")
            var flot,money;
            that.totalMoney="";
            that.cartList.forEach(function(val){
                val.products.forEach(function(key){
                    that.integralList.forEach(function(key1){
                        if(key1==key.cartId){
                            console.log("6666666")
                            console.log(key1)
                            that.totalMoney=Number(that.totalMoney)+Number(key.number)*Number(key.integral);
                            console.log(that.totalMoney)
                        }
                    });

                });
            });
            console.log("------------")
            console.log(that.totalMoney)
            console.log("------------")
        },
        //选中
        checkedAll:function(index){
            var that=this;
            var listTitle=$("#listTitle"+index);
            var len=listTitle.siblings(".shoppingCart-listCent").find("input[type=checkbox]");
            console.log(len.length)
            if(listTitle.hasClass("shoppingCart-select")){
                listTitle.removeClass("shoppingCart-select");
                for(var i=0;i<=len.length;i++){
                    if(len.eq(i).prop("disabled")==false){
                        console.log(len.eq(i).val())
                        that.integralList.splice($.inArray(len.eq(i).val(),that.integralList),1);
                    }
                }
            }else{
                listTitle.addClass("shoppingCart-select");
                var flat;
                console.log(len.prop("disabled").length)
                for(var i=0;i<=len.length;i++){
                    if(len.eq(i).prop("disabled")==false){
                        if(that.integralList.length>0){
                            flat=false;
                            that.integralList.forEach(function(val){
                                console.log(val!=len.eq(i).val())
                                if($.inArray(len.eq(i).val(),that.integralList)==-1){
                                    that.integralList.push(len.eq(i).val());
                                }
                            });
                        }else{
                            that.integralList.push(len.eq(i).val());
                        }

                    }
                }
            }
        },
        getPreorder:function(){
            var that=this;
            if(that.integralList.length>0){
                location.href="/purchase/confirmOrder?uid="+that.uid+"&cartId="+that.integralList.join(",");
            }else{
                vm.$refs.prompt.toast("请选择商品！");
            }

        },
        getClass:function(list,ins){
            if(list.activityType!=null&&ins!=0){
                return "list-cent1"
            }else if(list.activityType!=null&&ins==0){
                return "list-cent2"
            }
            //[list.activityType!=null&&ins!=0?'':'list-cent2']
        },
        getEdit:function(type){
            this.type=type;
        },
        getNext:function(list){
            if(list.mediaUserId){
                location.href="/userGoodsInfo?productId="+list.productId;
            }else{
                location.href="/purchase/goodsDetails?type=1&productId="+list.productId;
            }
        }
    },
    watch:{
        integralList:function(){
            var that=this;
            console.log(this.integralList)
            that.countMoney();
            var shoppingCart=$(".shoppingCart-list");
            that.$nextTick(function(){
                shoppingCart.each(function(ins,val){
                    console.log("++++++++++++++++")
                    console.log("input个数"+$(val).find("input[type=checkbox]").length)
                    console.log("禁用个数"+$(val).find("input:disabled").length)
                    console.log("选中个数"+$(val).find("input:checked").length)
                    var len=$(val).find("input[type=checkbox]").length;
                    var len1=$(val).find("input:disabled").length;
                    var len2=$(val).find("input:checked").length;
                    var listTitle=$(val).find(".shoppingCart-listTitle");
                    if(len==len2||len==(len1+len2)){
                        console.log("1111")
                        listTitle.addClass("shoppingCart-select")
                    }else if(len!=len2){
                        listTitle.removeClass("shoppingCart-select")
                    }
                });
                var leng=$(".shoppingCart").find(".shoppingCart-select").length;
                if(leng==that.cartList.length){
                    $(".checkboxCart").addClass("shoppingCart-select");
                }else{
                    $(".checkboxCart").removeClass("shoppingCart-select");
                }
            });
        },
        cartList:function(){
            this.$nextTick(function(){
                var that=this;
                var container = document.querySelectorAll('.list-centLeft');
                console.log(container)
                var expansion = null; //是否存在展开的list
                for(var i = 0; i < container.length; i++){
                    var x, y, X, Y, swipeX, swipeY;
                    container[i].addEventListener('touchstart', function(event) {
                        x = event.changedTouches[0].pageX;
                        y = event.changedTouches[0].pageY;
                        swipeX = true;
                        swipeY = true ;
                        if(expansion){   //判断是否展开，如果展开则收起
                            expansion.className ="list-centLeft";
                        }
                    });
                    container[i].addEventListener('touchmove', function(event){
                        event.stopPropagation();
                        X = event.changedTouches[0].pageX;
                        Y = event.changedTouches[0].pageY;
                        // 左右滑动
                        if(swipeX && Math.abs(X - x) - Math.abs(Y - y) > 0){
                            // 阻止事件冒泡
                            event.stopPropagation();
                            if(X - x > 10){   //右滑
                                event.preventDefault();
                                this.className = "list-centLeft";    //右滑收起
                                //console.log("右滑")
                            }
                            if(x - X > 10){   //左滑
                                event.preventDefault();
                                this.className = "list-centLeft swipeleft";   //左滑展开
                                //console.log("左滑")
                                expansion = this;
                            }
                            swipeY = false;
                        }
                        // 上下滑动
                        if(swipeY && Math.abs(X - x) - Math.abs(Y - y) < 0) {
                            swipeX = false;
                        }
                    });
                }
            });
        }
    }
});
var addTimer = function () {
    var list = [],
        interval;

    return function (id, time) {
        if (!interval)
            interval = setInterval(go, 1000);
        list.push({ ele: document.getElementById(id), time: time });
    };
    function go() {
        for (var i = 0; i < list.length; i++) {
            list[i].ele.innerHTML= getTimerString(list[i].time ? list[i].time -= 1 : 0);
            if (!list[i].time)
                list.splice(i--, 1);
        }
    }
    function getTimerString(time) {
        h = Math.floor(time/ 3600);
        m = Math.floor((time% 3600) / 60);
        s = Math.floor((time% 3600) % 60);
        if (time>0)
            return checkTime(h) + ":" + checkTime(m) + ":" + checkTime(s);
        else return "时间到";
    }
    function checkTime(i) {
        if (i<10) {
            i = "0" +i;
        }
        return i;
    }
} ();
//比较日前大小
function getCompareDate(startTime, endTime, diffType) {
    startTime = JSON.stringify(startTime).split("-").join("/");//replace(/-/g, '/')
    endTime = JSON.stringify(endTime).split("-").join("/");
    //将计算间隔类性字符转换为小写
    diffType = diffType.toLowerCase();
    var sTime =new Date(JSON.parse(startTime)); //开始时间
    var eTime =new Date(JSON.parse(endTime)); //结束时间
    //作为除数的数字
    var timeType =1;
    switch (diffType) {
        case"second":
            timeType =1000;
            break;
        case"minute":
            timeType =1000*60;
            break;
        case"hour":
            timeType =1000*3600;
            break;
        case"day":
            timeType =1000*3600*24;
            break;
        default:
            break;
    }
    return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType));
}
// function checkTime(i){ //将0-9的数字前面加上0，例1变为01
//     if(i<10){
//         i = "0" + i;
//     }
//     return i;
// }